package com.example.demo2.util;

import java.io.*;

/**
 * @Author kordgi
 * @Date 2022.04.27 0:17
 * @Description
 */

public class ChangeWord {
    public static void changeText(String s, String path, String target) {
        File fileText=new File(path);
        String text = s;
        if(fileText.canExecute()) //如果文件存在就继续
            setText(fileText,target,text); //爱改啥改啥
    }

    private static void setText(File fileText, String target, String src) {//修改
        BufferedReader br = null;
        PrintWriter pw = null;
        StringBuffer buff = new StringBuffer();
        String line=System.getProperty("line.separator");
        try {
            br=new BufferedReader(new FileReader(fileText));
            for(String str = br.readLine(); str != null; str=br.readLine()) {
                if(str.contains(target))
                    str = str.replaceAll(target, src);
                buff.append(str + line);
            }
            pw=new PrintWriter(new FileWriter(fileText),true);
            pw.println(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(pw != null)
                pw.close();
        }
    }
}
